// Rockwood CFS评估逻辑配置文件
import { rockwoodConfig } from './rockwoodConfig.js';

export const rockwoodLogic = {
  // 评估计算规则
  assessmentRules: {
    // CFS评分计算
    calculateCFS: (formData) => {
      const cfsScore = parseInt(formData.cfsScore);
      const level = rockwoodConfig.frailtyLevels[cfsScore];
      
      return {
        score: cfsScore,
        level: level.name,
        category: level.categoryName,
        description: level.description,
        color: level.color,
        recommendations: level.recommendations
      };
    },

    // 功能状态评估
    assessFunctionalStatus: (formData) => {
      const functionalMap = {
        'independent': { score: 1, description: '完全独立' },
        'minimal_help': { score: 2, description: '偶尔需要轻微帮助' },
        'moderate_help': { score: 3, description: '经常需要中等程度帮助' },
        'significant_help': { score: 4, description: '需要大量帮助' },
        'total_dependence': { score: 5, description: '完全依赖他人' }
      };
      
      return functionalMap[formData.functionalAssessment] || { score: 0, description: '未评估' };
    },

    // 活动能力评估
    assessMobility: (formData) => {
      const mobilityMap = {
        'very_active': { score: 1, description: '非常活跃，经常运动' },
        'active': { score: 2, description: '活跃，偶尔运动' },
        'limited_activity': { score: 3, description: '活动受限，但能独立行走' },
        'slow_walking': { score: 4, description: '行走缓慢，可能需要辅助' },
        'wheelchair': { score: 5, description: '需要轮椅或长期卧床' }
      };
      
      return mobilityMap[formData.mobilityLevel] || { score: 0, description: '未评估' };
    }
  },

  // 统计分析规则
  statisticsRules: {
    // 计算CFS评分分布
    calculateCFSDistribution: (surveys) => {
      const distribution = {};
      const total = surveys.length;
      
      // 初始化分布统计
      for (let i = 1; i <= 9; i++) {
        distribution[i] = {
          count: 0,
          percentage: 0,
          level: rockwoodConfig.frailtyLevels[i].name,
          category: rockwoodConfig.frailtyLevels[i].categoryName
        };
      }
      
      // 统计各等级数量
      surveys.forEach(survey => {
        const score = parseInt(survey.cfsScore);
        if (score >= 1 && score <= 9) {
          distribution[score].count++;
        }
      });
      
      // 计算百分比
      Object.keys(distribution).forEach(score => {
        distribution[score].percentage = total > 0 ? 
          ((distribution[score].count / total) * 100).toFixed(1) : 0;
      });
      
      return distribution;
    },

    // 计算分类统计
    calculateCategoryStats: (surveys) => {
      const categories = {
        'robust': { name: '健壮', count: 0, scores: [1, 2, 3] },
        'vulnerable': { name: '易损', count: 0, scores: [4] },
        'frail': { name: '衰弱', count: 0, scores: [5, 6, 7, 8] },
        'terminal': { name: '终末期', count: 0, scores: [9] }
      };
      
      surveys.forEach(survey => {
        const score = parseInt(survey.cfsScore);
        Object.keys(categories).forEach(category => {
          if (categories[category].scores.includes(score)) {
            categories[category].count++;
          }
        });
      });
      
      const total = surveys.length;
      Object.keys(categories).forEach(category => {
        categories[category].percentage = total > 0 ? 
          ((categories[category].count / total) * 100).toFixed(1) : 0;
      });
      
      return categories;
    },

    // 计算基本统计信息
    calculateBasicStats: (surveys) => {
      if (surveys.length === 0) {
        return {
          total: 0,
          averageAge: 0,
          genderDistribution: { male: 0, female: 0 },
          averageCFS: 0,
          mostCommonLevel: '无数据'
        };
      }

      const total = surveys.length;
      const totalAge = surveys.reduce((sum, survey) => sum + (survey.age || 0), 0);
      const averageAge = (totalAge / total).toFixed(1);
      
      const genderDistribution = surveys.reduce((acc, survey) => {
        if (survey.gender === 'male') acc.male++;
        else if (survey.gender === 'female') acc.female++;
        return acc;
      }, { male: 0, female: 0 });
      
      const totalCFS = surveys.reduce((sum, survey) => sum + parseInt(survey.cfsScore || 0), 0);
      const averageCFS = (totalCFS / total).toFixed(1);
      
      // 找出最常见的等级
      const levelCounts = {};
      surveys.forEach(survey => {
        const score = parseInt(survey.cfsScore);
        const level = rockwoodConfig.frailtyLevels[score]?.name || '未知';
        levelCounts[level] = (levelCounts[level] || 0) + 1;
      });
      
      const mostCommonLevel = Object.keys(levelCounts).reduce((a, b) => 
        levelCounts[a] > levelCounts[b] ? a : b, '无数据');
      
      return {
        total,
        averageAge,
        genderDistribution,
        averageCFS,
        mostCommonLevel
      };
    }
  },

  // 报告模板
  reportTemplates: {
    // 个人评估报告
    individualReport: (survey, recorderInfo) => {
      const cfsResult = rockwoodLogic.assessmentRules.calculateCFS(survey);
      const functionalResult = rockwoodLogic.assessmentRules.assessFunctionalStatus(survey);
      const mobilityResult = rockwoodLogic.assessmentRules.assessMobility(survey);
      
      const bmi = (survey.height && survey.weight) ? 
        (survey.weight / Math.pow(survey.height / 100, 2)).toFixed(1) : '未测量';
      
      const timestamp = new Date().toLocaleString('zh-CN');
      const recordTime = survey.recordTime ? 
        new Date(survey.recordTime).toLocaleString('zh-CN') : timestamp;

      return `Rockwood临床衰弱量表(CFS)评估报告
问答编号：${recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${recorderInfo.name}
记录人职务/身份：${recorderInfo.position}
所属机构：${recorderInfo.institution || '未填写'}
联系方式：${recorderInfo.contact || '未填写'}
记录时间：${recordTime}
备注：${survey.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${survey.patientName}
年龄：${survey.age}岁
性别：${survey.gender === 'male' ? '男性' : '女性'}
身高：${survey.height ? survey.height + 'cm' : '未测量'}
体重：${survey.weight ? survey.weight + 'kg' : '未测量'}
BMI：${bmi}
联系电话：${survey.phone || '未填写'}

=== Rockwood CFS评估结果 ===
CFS评分：${cfsResult.score}分
衰弱等级：${cfsResult.level}
分类：${cfsResult.category}
等级描述：${cfsResult.description}

=== 补充评估结果 ===
功能状态：${functionalResult.description}
活动能力：${mobilityResult.description}

=== 建议措施 ===
${cfsResult.recommendations.map((rec, index) => `${index + 1}. ${rec}`).join('\n')}

=== 评估说明 ===
Rockwood临床衰弱量表(CFS)是一个9分制的评估工具：
• 1-3分：健壮至管理良好的慢性疾病
• 4分：易损状态  
• 5-6分：轻度至中度衰弱
• 7-8分：重度至极重度衰弱
• 9分：终末期状态

本评估结果仅供临床参考，具体诊疗方案请咨询专业医师。

评估完成时间：${timestamp}
评估工具版本：Rockwood CFS v1.0.0`;
    },

    // 汇总统计报告
    summaryReport: (surveys, recorderInfo, statistics) => {
      const timestamp = new Date().toLocaleString('zh-CN');
      
      return `Rockwood CFS评估数据汇总报告
问答编号：${recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${recorderInfo.name}
记录人职务/身份：${recorderInfo.position}
所属机构：${recorderInfo.institution || '未填写'}
联系方式：${recorderInfo.contact || '未填写'}

=== 数据概览 ===
总评估人数：${statistics.basic.total}人
平均年龄：${statistics.basic.averageAge}岁
性别分布：男性${statistics.basic.genderDistribution.male}人，女性${statistics.basic.genderDistribution.female}人
平均CFS评分：${statistics.basic.averageCFS}分
最常见等级：${statistics.basic.mostCommonLevel}

=== CFS评分分布 ===
${Object.keys(statistics.distribution).map(score => {
  const data = statistics.distribution[score];
  return `${score}分 (${data.level})：${data.count}人 (${data.percentage}%)`;
}).join('\n')}

=== 分类统计 ===
${Object.keys(statistics.categories).map(category => {
  const data = statistics.categories[category];
  return `${data.name}：${data.count}人 (${data.percentage}%)`;
}).join('\n')}

=== 评估建议 ===
1. 对于健壮人群(1-3分)：继续保持良好的生活方式和健康习惯
2. 对于易损人群(4分)：加强预防措施，定期监测功能状态
3. 对于衰弱人群(5-8分)：制定个性化的干预和护理方案
4. 对于终末期人群(9分)：提供适当的临终关怀服务

报告生成时间：${timestamp}
评估工具：Rockwood临床衰弱量表(CFS) v1.0.0`;
    },

    // 详细数据CSV格式
    detailsCSV: (surveys) => {
      const headers = [
        '序号', '姓名', '年龄', '性别', '身高(cm)', '体重(kg)', 'BMI',
        'CFS评分', '衰弱等级', '分类', '功能状态', '活动能力',
        '联系电话', '记录时间', '备注'
      ];
      
      const rows = surveys.map((survey, index) => {
        const cfsResult = rockwoodLogic.assessmentRules.calculateCFS(survey);
        const functionalResult = rockwoodLogic.assessmentRules.assessFunctionalStatus(survey);
        const mobilityResult = rockwoodLogic.assessmentRules.assessMobility(survey);
        
        const bmi = (survey.height && survey.weight) ? 
          (survey.weight / Math.pow(survey.height / 100, 2)).toFixed(1) : '';
        
        const recordTime = survey.recordTime ? 
          new Date(survey.recordTime).toLocaleString('zh-CN') : '';
        
        return [
          index + 1,
          survey.patientName || '',
          survey.age || '',
          survey.gender === 'male' ? '男性' : survey.gender === 'female' ? '女性' : '',
          survey.height || '',
          survey.weight || '',
          bmi,
          cfsResult.score,
          cfsResult.level,
          cfsResult.category,
          functionalResult.description,
          mobilityResult.description,
          survey.phone || '',
          recordTime,
          survey.remarks || ''
        ];
      });
      
      return [headers, ...rows].map(row => row.join(',')).join('\n');
    },

    // 生成个人评估报告（用于保存）
    assessmentReport: (formData, recorderInfo, result, bmi) => {
      const timestamp = new Date().toLocaleString('zh-CN');
      const recordTime = formData.recordTime ? 
        new Date(formData.recordTime).toLocaleString('zh-CN') : timestamp;

      return `Rockwood临床衰弱量表(CFS)评估报告
问答编号：${recorderInfo.surveyId}
生成时间：${timestamp}

=== 记录人信息 ===
记录人姓名：${recorderInfo.name}
记录人职务/身份：${recorderInfo.position}
所属机构：${recorderInfo.institution || '未填写'}
联系方式：${recorderInfo.contact || '未填写'}
记录时间：${recordTime}
备注：${formData.remarks || '无'}

=== 被评估人基本信息 ===
姓名：${formData.patientName}
年龄：${formData.age}岁
性别：${formData.gender === 'male' ? '男性' : '女性'}
身高：${formData.height ? formData.height + 'cm' : '未测量'}
体重：${formData.weight ? formData.weight + 'kg' : '未测量'}
BMI：${bmi > 0 ? bmi.toFixed(1) : '未计算'}
联系电话：${formData.phone || '未填写'}

=== Rockwood CFS评估结果 ===
CFS评分：${result.score}分
衰弱等级：${result.level}
分类：${result.category}
等级描述：${result.description}

=== 补充评估结果 ===
功能状态：${result.functionalStatus}
活动能力：${result.mobilityLevel}

=== 建议措施 ===
${result.recommendations.map((rec, index) => `${index + 1}. ${rec}`).join('\n')}

=== 评估说明 ===
Rockwood临床衰弱量表(CFS)是一个9分制的评估工具：
• 1-3分：健壮至管理良好的慢性疾病
• 4分：易损状态
• 5-6分：轻度至中度衰弱  
• 7-8分：重度至极重度衰弱
• 9分：终末期状态

本评估结果仅供临床参考，具体诊疗方案请咨询专业医师。

评估完成时间：${timestamp}
评估工具版本：Rockwood CFS v1.0.0`;
    }
  },

  // 生成汇总报告
  generateSummaryReport: (surveys, statistics, recorderInfo) => {
    return rockwoodLogic.reportTemplates.summaryReport(surveys, recorderInfo, statistics);
  },

  // 生成详细CSV
  generateDetailedCSV: (surveys) => {
    return rockwoodLogic.reportTemplates.detailsCSV(surveys);
  },

  // 生成个人报告
  generateIndividualReport: (survey, recorderInfo) => {
    return rockwoodLogic.reportTemplates.individualReport(survey, recorderInfo);
  }
};

// 主要评估计算函数
export const calculateRockwoodAssessment = (formData) => {
  const cfsResult = rockwoodLogic.assessmentRules.calculateCFS(formData);
  const functionalResult = rockwoodLogic.assessmentRules.assessFunctionalStatus(formData);
  const mobilityResult = rockwoodLogic.assessmentRules.assessMobility(formData);
  
  return {
    score: cfsResult.score,
    level: cfsResult.level,
    category: cfsResult.category,
    description: cfsResult.description,
    color: cfsResult.color,
    recommendations: cfsResult.recommendations,
    functionalStatus: functionalResult.description,
    mobilityLevel: mobilityResult.description
  };
};

// 统计计算函数
export const calculateRockwoodStatistics = (surveys) => {
  return {
    distribution: rockwoodLogic.statisticsRules.calculateCFSDistribution(surveys),
    categories: rockwoodLogic.statisticsRules.calculateCategoryStats(surveys),
    basic: rockwoodLogic.statisticsRules.calculateBasicStats(surveys)
  };
};